package com.example.springfeature.service;

import com.example.springfeature.event.UserRegisterEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

//实现 ApplicationEventPublisherAware 接口，从而将 ApplicationEventPublisher 注入到其中
@Service
public class UserService implements ApplicationEventPublisherAware {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //事件发布者 ApplicationEventPublisher：通过它，可以进行事件的发布。
    //ApplicationEventPublisher 是spring提供的，不需要程序员开发
    private ApplicationEventPublisher applicationEventPublisher;

    //实现 ApplicationEventPublisherAware 接口，
    // 必须要重写setApplicationEventPublisher方法
    //从而将 ApplicationEventPublisher 注入到其中
    //这里使用的就是set方法注入
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void register(String username) {
        // ... 执行注册逻辑
        logger.info("[register][执行用户({}) 的注册逻辑]", username);

        // ... 发布一个事件(事件由程序员开发)
        applicationEventPublisher.publishEvent(new UserRegisterEvent(this, username));
    }

}